package com.sina.finance.api.framework.controller;

import com.sina.finance.api.framework.constants.Constants;
import com.sina.finance.api.framework.constants.SpringBeanConstants;
import com.sina.finance.api.framework.response.JspResponse;
import com.sina.finance.api.framework.response.Response;
import com.sina.finance.api.framework.service.IAPIService;
import com.sina.finance.api.framework.service.ISecurityService;
import com.sina.finance.api.framework.utils.LogUtils;
import com.sina.finance.api.framework.utils.ModelAndViewUtils;
import com.sina.finance.api.framework.utils.SpringBeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Properties;

@Controller
@Scope("prototype")
public class FrontController {
//	Logger logger = Logger.getLogger(getClass());

	@Autowired
	private HttpServletRequest request;
	
	@Resource(name= SpringBeanConstants.SECURITY_SERVICE)
	private ISecurityService securityService;

	@Resource
	private Properties configProperties;

    @RequestMapping("/api")
    public ModelAndView execute() {
    	Date startTime = new Date();

		@SuppressWarnings("unchecked")
		Map<String, String[]> requestParams = request.getParameterMap();
		//logger.info("======== Begin to enter api execute the parameters are:"+JSONObject.fromObject(requestParams).toString());

		Response response = null;

		// 1. 验证request参数
//		response = securityService.verifyRequest(requestParams);

        String method = request.getParameter(Constants.SYS_PARAM_METHOD);

		//method = generateInnerMethodName(method);

		String format = request.getParameter(Constants.SYS_PARAM_FORMAT).toUpperCase();

        // 如果验证通过
		// 2. 通过适配器调用相应API
		IAPIService apiService = (IAPIService) SpringBeanUtils.getBean(method);

		response = apiService.doJob(requestParams);

//    	if(!response.getCallResult()) {
//    		method = "error";
//    	}

		ModelAndView mav = null;

		if (response instanceof JspResponse) {

			mav = new ModelAndView( ((JspResponse)response).getJsp(), ((JspResponse)response).getModel());

		} else {

			// 3. 将API结果映射为相应数据格式并返回
			mav = ModelAndViewUtils.getModelAndView(method, format, response);

		}

		String ip = request.getRemoteAddr();

		Date endTime = new Date();

        LogUtils.info(requestParams, startTime, endTime, response, ip);

        return mav;
    }


	@Deprecated
	private String generateInnerMethodName(String method) {
		if (method != null) {
			Properties properties = new Properties();

			try {
				properties.load(this.getClass().getResourceAsStream("/rop-config.properties"));
				String methodPrefix = properties.getProperty("methodPrefix");

				if (!methodPrefix.equals("")) {
					String[] split = method.split(methodPrefix);
					method = split.length == 2 ? split[1] : split[0];
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return method;
	}
}
